import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering

input_file = "F:/python学习资料/Python-Machine-Learning-Cookbook-master/Chapter04/data_perf.txt"

x = []
with open(input_file,'r') as f:
    for line in f.readlines():
        data = [float(i) for i in line.split(",")]
        x.append(data)

data = np.array(x)
scores = []
range_values = np.arange(2,10)
for i in range_values:
    # 训练模型
    # k-means聚类
    #kmeans = KMeans(init='k-means++',n_clusters=i,n_init=10)
    #kmeans.fit(data)
    # 凝聚分层聚类
    agg = AgglomerativeClustering(n_clusters=i)
    agg.fit(data)
    score = metrics.silhouette_score(data,agg.labels_,metric='euclidean',sample_size=len(data))
    print("Number of clusters=",i)
    print("Silhouette score=",score)
    scores.append(score)


# 画出图像找出峰值
# 画出得分柱状图
plt.figure()
plt.scatter(data[:,0],data[:,1],color='k',s=30,marker='o',facecolors='none')
x_min,x_max = min(data[:,0])-1,max(data[:,0])+1
y_min,y_max = min(data[:,1])-1,max(data[:,1])+1
plt.title("Input data")
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.xticks(())
plt.yticks(())
plt.show()